package com.example.arve;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Description:
 * Just a temporary thing to show the app can encode/decode QR codes
 * 
 * What's working:
 * - Encoding works fine. A string can be saved as a QR code and be stored as an image.
 * What's not:
 * - Decoding isn't working at the moment; I have a feeling that I've integrated zxing incorrectly, as stack
 *   overflow has a small truck load of solutions which I can't seem to utilize.
 * - Encoding doesn't show a preview of the image; it does store it on the phone though.
 * @author Richard
 */
public class QRActivity extends ActionBarActivity 
{
	private static final int PHOTO_SELECT_INTENT = 120;
	private EditText to_qr;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_qractivity);

		/*if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}*/
		to_qr = (EditText)findViewById(R.id.et_to_qr);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.qrscanner, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	/**
	 * Just encodes our text into a QR image
	 * @param _view The default view 
	 */
	public void generateQRCode(View _view)
	{
		//Make sure there's something to convert
		if(to_qr.getText().toString().length() != 0)
		{
			//Our QR encoder
			QRCodeWriter encoder = new QRCodeWriter();
			FileOutputStream fos = null;
			try
			{
				//Encode our message
				BitMatrix bm = encoder.encode(to_qr.getText().toString(), BarcodeFormat.QR_CODE, 400, 400);
				//Convert it to an image
				Bitmap qr_img = generateFromBitMatrix(bm);
				
				//Save it 
				File get_sdcard = new File(Environment.getExternalStorageDirectory(), "MyQRCodes");
				if(!get_sdcard.exists())
					if(!get_sdcard.mkdir())
						Log.d("generateQRCode", "Couldn't make directory");
				fos = new FileOutputStream(new File(get_sdcard, "QRCode_" + FileUri.dateToString() + ".jpg"));
				//Compress to the best quality possible; anything less could screw up the QR code
				boolean saved = qr_img.compress(Bitmap.CompressFormat.JPEG, 100, fos);
				if(saved)
				{
					//At the moment only shows a message; later should show a picture
					Toast.makeText(this, "QR Code generated!", Toast.LENGTH_LONG).show();
				}
				else
				{
					
				}
			}
			catch(Exception _error)
			{
				Log.e("generateQRCode", _error.toString());
			}
			finally
			{
				if(fos != null)
				{
					try
					{
						fos.close();
					}
					catch(Exception _error)
					{
						
					}
				}
			}
		}
		else
			Toast.makeText(this, "Please enter what you want to encode.", Toast.LENGTH_LONG).show();
	}
	
	/**
	 * Grabs the bitmatrix and converts it into a bitmap
	 * @param _bm The bit matrix we'll be taking from
	 * @return A QR code in image form
	 */
	private Bitmap generateFromBitMatrix(BitMatrix _bm) 
	{
		int width = _bm.getWidth();
		int height = _bm.getHeight();
		//Create the bitmap based on the dimensions
		Bitmap ret = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); //Stored as this for smaller memory
		for(int x = 0; x < width; ++x) //And fill with black and white based on the QR code!
			for(int y = 0; y < height; ++y)
				ret.setPixel(x, y, _bm.get(x, y) ? Color.BLACK : Color.WHITE); //Creating the actual bitmap
		
		return ret;
	}

	/**
	 * Should allow the user to find an image they have, then read the image for a QR code. 
	 * The QR code is then converted into a message.
	 * @param _view
	 */
	public void readQRCode(View _view)
	{
		//This is causing some funky exceptions
		/*Intent img_selector = new Intent(Intent.ACTION_PICK);
		img_selector.setType("MyQRCodes/*");
		startActivityForResult(img_selector, PHOTO_SELECT_INTENT);*/
	}
	
	@Override
	protected void onActivityResult(int _request_code, int _result_code, Intent _intent) 
	{ 
	    super.onActivityResult(_request_code, _result_code, _intent); 

	    switch(_request_code) 
	    { 
	    	case PHOTO_SELECT_INTENT:
	    	{
		        if(_result_code == RESULT_OK)
		        {  

		        }
		        break;
	    	}
	    }
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	/*
	public static class PlaceholderFragment extends Fragment 
	{

		public PlaceholderFragment() 
		{
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) 
		{
			View rootView = inflater.inflate(R.layout.fragment_qractivity,
					container, false);
			return rootView;
		}
	}*/
}
